from flask import Flask,redirect,url_for,request,render_template
from sqlalchemy import create_engine
from dbCon import DB_URI
from sqlalchemy.orm import sessionmaker
from model.entity import Users,Job1
from fuzzywuzzy import fuzz
from collections import Counter
import re
app=Flask(__name__)

user_name='momo'
# 把用户名定义成一个全局变量

@app.route('/')
# 欢迎界面
def welcome():
    return render_template("welcome.html")

@app.route('/login')
# 跳转到登陆页面login.html
def login():
    return render_template("login.html")

@app.route('/logininfo',methods=["post","get"])
# 接收login表单中的数据
def logininfo():
    global user_name
    user_name=request.form['name']
    password = request.form['pass']
    engine = create_engine(DB_URI, echo=False)
    Session = sessionmaker(bind=engine)
    session = Session()
    user = session.query(Users).filter(Users.user_name == user_name).first()
    if user is None:
    # 判断该用户名是否存在，若不存在，反馈给页面
        return render_template('login.html', flag=1)
    if password==user.password:
    # 判断两次输入的密码是否一致，若不一致，反馈给页面
        return render_template("main.html", user_name=user_name)
    if password!=user.password:
        return render_template('login.html', flag=1)

@app.route('/register')
# 跳转到注册页面register.html
def register():
    return render_template("register.html")

@app.route('/registerinfo',methods=["post","get"])
# 接收register表单中的数据
def registerinfo():
    global user_name
    user_name=request.form['name']
    password=request.form['pass']
    repassword=request.form['repass']
    engine = create_engine(DB_URI, echo=False)
    Session = sessionmaker(bind=engine)
    session = Session()
    user = session.query(Users).filter(Users.user_name == user_name).all()
    if len(user)!=0:
    # 判断此用户名是否被使用，若被使用，反馈给页面
        return render_template('register.html',flag=1)
    if  password==repassword:
    # 判断两次输入的密码是否一致，若一致，添加信息，否则，反馈给页面
        ed_users = Users(user_name=user_name, password=password)
        session.add(ed_users)
        session.commit()
        return render_template('login.html',user_name=user_name)
    else:
        return render_template('register.html',flag = 2)

@app.route('/index')
# 跳转到首页（推荐公司页面）index.html
def index():
    engine = create_engine(DB_URI, echo=False)
    Session = sessionmaker(bind=engine)
    session = Session()
    user = session.query(Users).filter(Users.user_name == user_name).first()
    job=session.query(Job1).all()
    res1=[]
    res2=[]
    res3=[]
    res4=[]
    if user.user_targetjob is not None:
    # 从job中筛选出符合职位要求的向量组，并写入res1
        for item in job:
            if fuzz.partial_ratio(item.job_name,user.user_targetjob)>80:
            # 筛选出职位匹配度大于80的job向量组
                res1.append(item)
    else: res1=job
    if user.user_targetcity is not None:
    # 从res1中筛选出符合城市要求的向量组，并写入res2
        for item in res1:
            if item.place==user.user_targetcity:
                res2.append(item)
    else: res2=res1
    if user.user_minsalary is not None:
    # 从res2中筛选出大于最低薪资要求要求的向量组，并写入res3
        for item in res2:
            if int(item.salary_min)*1000>int(user.user_minsalary):
                res3.append(item)
    else: res3=res2
    if user.user_maxsalary is not None:
    # 从res3中筛选出小于最高薪资要求的向量组，并写入res4
        for item in res3:
            if int(item.salary_max)*1000<=int(user.user_maxsalary):
                res4.append(item)
    else: res4=res3
    if len(res4)==0:
        return render_template('index.html',flag=0)
        # 如果没有找到符合所有要求的向量组，返回flag
    else:
        return render_template('index.html',**{'job':res4})

@app.route('/post')
# 跳转到职位分析页面post.html
def post():
    return render_template('post.html')

@app.route('/postinfo',methods=["GET","POST"])
# 接收post.html表单中的信息
def postinfo():
    # 表单获取搜索内容
    job_name=request.form['job_name']
    engine = create_engine(DB_URI, echo=False)
    Session = sessionmaker(bind=engine)
    session = Session()
    job = session.query(Job1).all()
    place=[]
    res=[]
    for item in job:
        if fuzz.partial_ratio(item.job_name, job_name) > 80:
            # 筛选出职位匹配度大于80的job向量组
            place.append(item.place)
            res.append(item)
    res1=[]
    res3=[]
    res2=list()
    if place is not None:
        res3=Counter(place)
        res1=res3.most_common(10)
    if res is not None:
        res2.append(["小于 3k", 0])
        res2.append(["3k-7k", 0])
        res2.append(["7k-10k", 0])
        res2.append(["10k-15k", 0])
        res2.append(["15k-20k", 0])
        res2.append(["大于 20k", 0])
        i=0
        for x in res:
            if int(x.salary_min) < 3:
                res2[0][1] = res2[0][1] + 1
            elif int(x.salary_min) >= 3 and int(x.salary_min) < 7:
                res2[1][1] = res2[1][1] + 1
            elif int(x.salary_min) >= 7 and int(x.salary_min) < 10:
                res2[2][1] = res2[2][1] + 1
            elif int(x.salary_min) >= 10 and int(x.salary_min) < 15:
                res2[3][1] = res2[3][1] + 1
            elif int(x.salary_min) >= 15 and int(x.salary_min) < 20:
                res2[4][1] = res2[4][1] + 1
            elif int(x.salary_min) >= 20:
                res2[5][1] = res2[5][1] + 1

    return render_template('post.html',place=res1,salary_min=res2,job_name=job_name,flag=1)

@app.route('/city')
# 跳转到城市分析页面city.html
def city():
    return render_template('city.html')

@app.route('/city/serach',methods=["post"])
# 接收city.html的表单信息
def city_serach():
    engine = create_engine(DB_URI, echo=False)
    Session = sessionmaker(bind=engine)
    session = Session()
    city=request.form['place']
    print(city)
    tag=session.query(Job1).filter(Job1.place==city).first()
    if tag is None:
        print("2")
        return render_template('city.html',flag = 1)
    res=session.query(Job1).filter(Job1.place==city).all()
    res1=list()
    res1.append(["小于 3k",0])
    res1.append(["3k-5k",0])
    res1.append(["5k-7k",0])
    res1.append(["7k-9k",0])
    res1.append(["9k-11k",0])
    res1.append(["大于 11k",0])
    for x in res:
        if int(x.salary_min) < 3:
            res1[0][1]=res1[0][1]+1
        elif int(x.salary_min)>=3 and int(x.salary_min) < 5:
            res1[1][1]=res1[1][1]+1
        elif int(x.salary_min)>=5 and int(x.salary_min) < 7:
            res1[2][1]=res1[2][1]+1
        elif int(x.salary_min)>=7 and int(x.salary_min) < 9:
            res1[3][1]=res1[3][1]+1
        elif int(x.salary_min)>=9 and int(x.salary_min) < 11:
            res1[4][1]=res1[4][1]+1
        elif int(x.salary_min)>=11:
            res1[5][1]=res1[5][1]+1
    return render_template('city.html',data=res1,city=city,flag2=1)

@app.route('/company')
# 跳转到公司性质分析页面company.html
def company():
    engine = create_engine(DB_URI, echo=False)
    Session = sessionmaker(bind=engine)
    session = Session()
    job = session.query(Job1).all()
    res=[]
    for item in job:
        res.append(item.company_type)
    res1=Counter(res)
    res2=res1.most_common(12)
    return render_template('company.html',**{'type':res2})

@app.route('/require')
# 跳转到职位需求分析页面require.html
def require():
    engine = create_engine(DB_URI, echo=False)
    Session = sessionmaker(bind=engine)
    session = Session()
    res = session.query(Job1).all()
    res1 = list()
    res1.append(["应届生", 0])
    res1.append(["1年以内经验", 0])
    res1.append(["1-3年经验", 0])
    res1.append(["3-5年经验", 0])
    res1.append(["5-10年经验", 0])
    res1.append(["10年以上经验", 0])
    for exp in res:
        if exp.experience=='在校生/应届生':
            res1[0][1] = res1[0][1] + 1
        elif exp.experience=='1年以内经验':
            res1[1][1] = res1[1][1] + 1
        elif exp.experience=='1-3年经验':
            res1[2][1] = res1[2][1] + 1
        elif exp.experience=='3-5年经验':
            res1[3][1] = res1[3][1] + 1
        elif exp.experience=='5-10年经验':
            res1[4][1] = res1[4][1] + 1
        elif exp.experience=='10年以上经验':
            res1[5][1] = res1[5][1] + 1
    res2 = list()
    res2.append(["学历不限", 0])
    res2.append(["初中", 0])
    res2.append(["中专", 0])
    res2.append(["高中", 0])
    res2.append(["大专", 0])
    res2.append(["本科", 0])
    res2.append(["硕士", 0])
    res2.append(["博士", 0])

    for edu in res:
        if edu.education == '学历不限':
            res2[0][1] = res2[0][1] + 1
        elif edu.education == '初中及以下':
            res2[1][1] = res2[1][1] + 1
        elif edu.education == '中技/中专':
            res2[2][1] = res2[2][1] + 1
        elif edu.education == '高中':
            res2[3][1] = res2[3][1] + 1
        elif edu.education == '大专':
            res2[4][1] = res2[4][1] + 1
        elif edu.education == '本科':
            res2[5][1] = res2[5][1] + 1
        elif edu.education == '硕士':
            res2[6][1] = res2[6][1] + 1
        elif edu.education == '博士':
            res2[7][1] = res2[7][1] + 1
    return render_template('require.html',data=res1, data1=res2,flag=1)


@app.route('/user_info')
# 跳转到修改信息页面user_information.html,并传递数据
def user_info():
    engine = create_engine(DB_URI, echo=False)
    Session = sessionmaker(bind=engine)
    session = Session()
    user = session.query(Users).filter(Users.user_name == user_name).first()
    # 表示当前信息数据暂未被修改
    return render_template("user_information.html",user=user)

@app.route('/user_infoAlter/<edict>')
# 跳转到修改信息页面user_information.html,提示信息修改成功，并传递修改后的数据数据
def user_infoAlter(edict):
    engine = create_engine(DB_URI, echo=False)
    Session = sessionmaker(bind=engine)
    session = Session()
    user = session.query(Users).filter(Users.user_name == user_name).first()
    return render_template("user_information.html",user=user,edict=edict)

@app.route('/user_information',methods=["post","get"])
# 接收添加/修改用户信息页面的数据
def user_information():
    password = request.form['pass']
    user_targetcity=request.form['city']
    user_targetjob=request.form['job']
    user_minsalary=request.form['minsalary']
    user_maxsalary=request.form['maxsalary']
    if user_targetcity=='':
        user_targetcity=None
    # 前端传到后端的空值需要令其为空
    if user_targetjob=='':
        user_targetjob=None
    if user_minsalary=='':
        user_minsalary=None
    if user_maxsalary=='':
        user_maxsalary=None
    engine = create_engine(DB_URI, echo=False)
    Session = sessionmaker(bind=engine)
    session = Session()
    user = session.query(Users).filter(Users.user_name == user_name).first()
    if password==user.password:
    #判断密码是否输入正确
       edict='修改成功'
       user.user_targetcity = user_targetcity
       user.user_targetjob = user_targetjob
       user.user_minsalary=user_minsalary
       user.user_maxsalary=user_maxsalary
    # 对user的数据进行更新，并传入数据库
       session.commit()
    else:
        edict='密码输入错误，修改失败'
    return redirect(url_for('user_infoAlter',edict=edict))
    # 信息修改成功，跳转到user_info_alter函数


@app.route('/wordcloud')
def wordcloud():
    return render_template("/wordcloud.html")



if __name__ == '__main__':
    app.run(debug=True)

